package com.jzo2o.orders.manager.listener;

import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.JsonUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.orders.manager.porperties.TradeProperties;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 订单状态监听器
 *
 * @Author mr.lin
 * @Date 2025/2/6 21:43
 */
@Component
public class OrderStatusUpdateListener {

    @Autowired
    private IOrdersCreateService ordersCreateService;


    @Resource
    private TradeProperties tradeProperties;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(name = MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenerMsg(String msg) {
        //1.判断是否有消息
        if (StringUtils.isBlank(msg)) {
            return;
        }
        //2.转化消息为List集合
        List<TradeStatusMsg> tradeStatusMsgList = JsonUtils.toList(msg, TradeStatusMsg.class);
        if (CollUtils.isEmpty(tradeStatusMsgList)) {
            return;
        }
        //3.遍历集合 先过滤(只要订单微服务的数据) 再修改订单状态
        tradeStatusMsgList.stream().filter(tsm ->
                ObjectUtils.equals(tsm.getProductAppId(), tradeProperties.getProductAppId()) && ObjectUtils.equals(tsm.getStatusCode(), TradingStateEnum.YJS.getCode())
        ).forEach(t -> ordersCreateService.paySuccess(t.getProductOrderNo(), t.getPaySuccessTime(), t.getTransactionId()));
    }
}
